import { createStore } from 'vuex'
import axios from 'axios'
export default createStore({
  // 数据仓库
  state: {
    titleArr: [],
    list: [],
    token: ''
  },
  // 计算属性
  getters: {},
  // 处理逻辑->同步
  mutations: {
    SET_TITLE(state, arr) {
      state.titleArr = arr
    },
    SET_LIST(state, list) {
      state.list = list
    }
  },
  // 处理异步
  // 请求接口，处理异步数据
  actions: {
    async fetch_login({ commit }) {
      try {
        const response = await axios.get('http://localhost:9999/navTitle')
        console.log('response:', response.data)
        return { code: 0, msg: 'success', data: response.data }
      } catch (error) {
        return { code: -1, msg: 'fail' }
      }
    },
    // async 返回什么? promise
    async fetch_title({ commit }, callback) {
      // axios.get('http://localhost:9999/navTitle').then((res) => {
      //   console.log('store=>res:', res.data)
      //   commit('SET_TITLE', res.data)
      //   // 回调传递参数
      //   callback && callback(res.data)
      // })
      const response = await axios.get('http://localhost:9999/navTitle')
      console.log('response:', response.data)
      // 将数据传递给了mutations
      commit('SET_TITLE', response.data)
      // 将数据传递给组件，方便组件做出后续操作
      return { code: 0, msg: 'success', data: response.data }
    },
    async fetch_list({ commit }, { page, size }) {
      const response = await axios.get('http://localhost:9999/list', {
        params: { _page: page, _limit: size }
      })
      console.log('response:', response.data)
      commit('SET_LIST', response.data)
    }
  },
  modules: {}
})
